package com.pmantra.loanwolf.server;

import com.google.api.gwt.oauth2.client.Auth;
import com.google.api.gwt.oauth2.client.AuthRequest;
import com.google.api.gwt.oauth2.client.Callback;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.pmantra.loanwolf.client.GreetingService;
import com.pmantra.loanwolf.shared.FieldVerifier;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {

	public String greetServer(String input) throws IllegalArgumentException {
		// Verify that the input is valid. 
		if (!FieldVerifier.isValidName(input)) {
			// If the input is not valid, throw an IllegalArgumentException back to
			// the client.
			throw new IllegalArgumentException(
					"Name must be at least 4 characters long");
		}

		String serverInfo = getServletContext().getServerInfo();
		String userAgent = getThreadLocalRequest().getHeader("User-Agent");

		// Escape data from the client to avoid cross-site script vulnerabilities.
		input = escapeHtml(input);
		userAgent = escapeHtml(userAgent);

		return "Hello, " + input + "!<br><br>I am running " + serverInfo
				+ ".<br><br>It looks like you are using:<br>" + userAgent;
	}

	/**
	 * Escape an html string. Escaping data received from the client helps to
	 * prevent cross-site script vulnerabilities.
	 * 
	 * @param html the html string to escape
	 * @return the escaped string
	 */
	private String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;");
	}

	@Override
	public String googleOauth() {

		String AUTH_URL = "https://accounts.google.com/o/oauth2/auth";
		String CLIENT_ID = "887016388939.apps.googleusercontent.com";
		String SCOPE_READONLY_EMAIL = "https://www.googleapis.com/auth/userinfo.email";
		
		AuthRequest req = new AuthRequest(AUTH_URL, CLIENT_ID)
		    .withScopes(SCOPE_READONLY_EMAIL);
		
		Auth.get().login(req, new Callback<String, Throwable>() {
			  @Override
			  public void onSuccess(String token) {
			    // You now have the OAuth2 token needed to sign authenticated requests.
			  }
			  @Override
			  public void onFailure(Throwable caught) {
			    // The authentication process failed for some reason, see caught.getMessage()
			  }
			});
		
		return null;
	
	}
}
